package com.flats.model.dao.hibernate;

import com.flats.model.dao.Dao;
import com.flats.model.entity.Address;
import com.flats.model.entity.Persistent;
import org.hibernate.*;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

@Transactional
public class AddressHibernateDao extends AbstractHibernateDao<Address> {

    @Override
    @Transactional
    public Serializable saveOrUpdate(Address persistent) {
        getSession().beginTransaction();
        Serializable id =getSession().save(persistent);
        getSession().getTransaction().commit();
        return id;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        String query="delete from \"ROOT_USER\".\"ADDRESS\" where ADDRESS_ID ="+id.toString();
        SQLQuery sqlQuery = getSession().createSQLQuery(query);
        sqlQuery.executeUpdate();
    }

    @Override
    @Transactional
    public void delete(Address persistent) {
        getSession().delete(persistent);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public Address get(Long id) {
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
//        getSession();
//        getSession().beginTransaction();
//        String query="select *\n" +
//                "from ROOT_USER.ADDRESS\"\n" +
//                "where \"ADDRESS_ID\"="+id.toString();
//        List<Address> addressList = getSession().createSQLQuery(query).addEntity(Address.class).list();
//        System.out.println("GET one address from addressList = " + addressList);
//        return addressList.iterator().next();
        return (Address) getSession().load(Address.class,id);

    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public List<Address> getAll() {
//        getSession();
//        getSession().beginTransaction();
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        String query="select * from ROOT_USER.ADDRESS";
        List<Address> addressList = getSession().createSQLQuery(query)
                .addEntity(Address.class)
                .list();
        return addressList;
    }

}
